package com.nitty.cash.loop.ui.dialog

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.lib.common.permission.CommonPermissions
import com.lib.common.permission.OnPermissionCallback
import com.lib.common.permission.Permission
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonDialog
import com.nitty.cash.loop.configs.NittyApiPath
import com.nitty.cash.loop.configs.NittyApiUrl
import com.nitty.cash.loop.configs.NittyConfigs
import com.nitty.cash.loop.databinding.DialogCustomerBinding
import com.nitty.cash.loop.event.NittyEventPointHelper
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.request.IHttpCallback
import com.nitty.cash.loop.ui.adapter.NittyCustomerAdapter
import com.nitty.cash.loop.utils.helper.NittyConfigsHelper
import com.nitty.cash.loop.utils.shared.NittySharedHelper
import com.nitty.cash.loop.utils.shared.NittySharedKey
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/15 10:29
 * @Annotation：联系客服Dialog
 */
class NittyCustomerDialog(context: Context) : CommonDialog(context) {
    lateinit var binding: DialogCustomerBinding
    private var callback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //产品名称
    private var pName = NittyConfigs.NITTY_APPNAME
    //产品Token
    private var pToken = NittySharedHelper.getNittySharedString(NittySharedKey.NITTY_TOKEN)
    //客服联系方式列表
    private var customerAdapter: NittyCustomerAdapter? = null

    override fun getRootView(): View {
        binding = DialogCustomerBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initCustomerListView()
    }

    override fun initListener() {
        setOnClickListener(binding.customerClose)
    }

    override fun loadData() {
        //主产品
        if (this.pName == NittyConfigs.NITTY_APPNAME){
            val commonInfo = NittySharedHelper.getNittySharedString(NittySharedKey.NITTY_COMMON)
            if (commonInfo.isEmpty()){
                loadCustomerContactListAction()
                return
            }
            val data = JSONObject(commonInfo)
            setCustomerContactData(data)
        } else {
            loadCustomerContactListAction()
        }
    }

    override fun onViewClick(v: View?) {
        dismiss()
    }

    /**
     * 事件备注
     */
    fun setCustomerEventRemark(remark: String): NittyCustomerDialog{
        this.eventRemark = remark
        return this
    }

    /**
     * 对应的产品名称
     */
    fun setCustomerProductName(name: String): NittyCustomerDialog{
        if (name.isNotEmpty()){
            this.pName = name
        }
        return this
    }

    /**
     * 对应的产品Token
     */
    fun setCustomerProductToken(token: String): NittyCustomerDialog{
        if (pToken.isNotEmpty()){
            this.pToken = token
        }
        return this
    }

    /**
     * 设置监听回调
     */
    fun setCustomerClickCallback(callback: IDialogCallback): NittyCustomerDialog{
        this.callback = callback
        return this
    }

    fun setCustomerCancelable(flag: Boolean): NittyCustomerDialog{
        setCancelable(flag)
        return this
    }

    fun setCustomerCanceledOnTouchOutside(flag: Boolean): NittyCustomerDialog{
        setCanceledOnTouchOutside(flag)
        return this
    }

    /**
     * 初始化Tab列表
     */
    private fun initCustomerListView() {
        binding.customerTime.visibility = View.GONE
        binding.customerListView.visibility = View.GONE
        binding.customerListView.layoutManager = LinearLayoutManager(context)
        customerAdapter = NittyCustomerAdapter(binding.customerListView)
        binding.customerListView.adapter = customerAdapter
        binding.customerListView.itemAnimator = DefaultItemAnimator()
        customerAdapter!!.setOnItemChildClickListener(CommonOnItemChildClickListener { _, childView, position ->
            val item = customerAdapter!!.getItem(position)
            if (childView.id == R.id.btnCustomer) {
                when (item.optString("type")) {
                    "MOBILE" -> {//电话
                        if (CommonPermissions.isGranted(context, Permission.CALL_PHONE)) {
                            onCustomerMobileCallAction(item)
                        } else {
                            CommonPermissions.with(context)
                                .permission(Permission.CALL_PHONE)
                                .request(object : OnPermissionCallback {
                                    override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                        NittyEventPointHelper.addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_SYSTEM_AGREE, Permission.CALL_PHONE)
                                        onCustomerMobileCallAction(item)
                                    }
                                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                        NittyEventPointHelper.addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_PERMISSION_SYSTEM_DENY, Permission.CALL_PHONE)
                                        CommonPermissions.startPermissionActivity(context, Permission.CALL_PHONE)
                                    }
                                })
                        }
                    }

                    else -> {//邮箱
                        onCustomerEmailCopyAction(item)
                    }
                }
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    private fun loadCustomerContactListAction(){
        val params = JSONObject().apply {
            put("path",NittyApiPath.NITTY_PATH.NITTY_API_APP_INFO_PATH)
            put("product",pName)
            put("token",pToken)
        }
        val httpUrl = NittyApiUrl.getHttpUrl()
        doPostAction(httpUrl, params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        //保存所有数据
                        if (obj != null) {
                            setCustomerContactData(obj)
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                showNittyToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    @SuppressLint("SetTextI18n")
    private fun setCustomerContactData(data: JSONObject){
        binding.customerTime.visibility = View.VISIBLE
        binding.customerListView.visibility = View.VISIBLE
        val contactList = arrayListOf<JSONObject>()
        val customize = data.optJSONObject("customize")
        if (customize != null){
            val mobileList = customize.optString("mobile").split(",")
            for (i in mobileList.indices){
                val obj = JSONObject()
                obj.put("type","MOBILE")
                obj.put("value", mobileList[i])
                contactList.add(obj)
            }
            val emailList = customize.optString("email").split(",")
            for (i in emailList.indices){
                val obj = JSONObject()
                obj.put("type","EMAIL")
                obj.put("value", emailList[i])
                contactList.add(obj)
            }
        }
        customerAdapter!!.data = contactList

        //工作时间
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workDate = "Monday to Sunday"
        var workTime = "9:30am to 19:30pm."
        val customData = customize!!.optJSONObject("customData")
        if (customData != null){
            if (!customData.has("workDate") || !customData.has("workTime")){
                val commonCustomData = NittyConfigsHelper.getNittyCustomData()
                if (commonCustomData != null) {
                    customData.put("workDate",commonCustomData.optString("workDate"))
                    customData.put("workTime",commonCustomData.optString("workTime"))
                }
            }
            workDate = customData.optString("workDate")
            workTime = customData.optString("workTime")
        }
        binding.customerTime.text = "$workDate,$workTime"
    }

    /**
     * 复制
     */
    private fun onCustomerEmailCopyAction(item: JSONObject){
        val type = item.optString("type")
        NittyEventPointHelper.addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_KEFU_COPY,type + "：" + item.optString("value"))
        // 获取剪贴板管理器
        val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个 ClipData 对象，将要复制的文本放入其中
        val clipData = ClipData.newPlainText("label", item.optString("value"))
        // 将 ClipData 对象放入剪贴板
        clipboardManager.setPrimaryClip(clipData)
        showNittyToast(getString(R.string.customer_email_copy_success))
    }

    /**
     * 拨号
     */
    private fun onCustomerMobileCallAction(item: JSONObject){
        val type = item.optString("type")
        NittyEventPointHelper.addEventPointRequestAction(NittyEventPointType.CLICK.NITTY_CLICK_KEFU_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        context.startActivity(callIntent)
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    override fun onStart() {
        super.onStart()
        NittyEventPointHelper.addEventPointRequestAction(NittyEventPointType.DIALOG.NITTY_DIALOG_CUSTOMER_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        NittyEventPointHelper.addEventPointRequestAction(NittyEventPointType.DIALOG.NITTY_DIALOG_CUSTOMER_DISMISS,eventRemark)
    }
}